#!/bin/sh
# Build SD card image

BOARD_ID="${1}" # For example "bananapi"
CHIP_ID="${2}" # For example "allwinner-a10"
DEFCONFIG="${3}" # For example "Bananapi_defconfig"
TUPLE="${4}" # For example "arm-linux-gnueabihf"

set -ex

RPI_FIRMWARE_GIT_URL_DEFAULT="https://github.com/raspberrypi/firmware/"

if [ ! -z "${RPI_FIRMWARE_GIT_REV}" ]
then
	git clone --depth 1 \
	          --reference-if-able "${WORKDIR}/rpi-firmware" \
	          --branch "${RPI_FIRMWARE_GIT_REV}" \
	          "${RPI_FIRMWARE_GIT_URL:-${RPI_FIRMWARE_GIT_URL_DEFAULT}}" rpi-firmware
else
	git clone --depth 1 \
	          --reference-if-able "${WORKDIR}/rpi-firmware" \
	          --branch stable \
	          "${RPI_FIRMWARE_GIT_URL:-${RPI_FIRMWARE_GIT_URL_DEFAULT}}" rpi-firmware
fi

# Collect version of firmware
(echo -n rpi-firmware,; git -C rpi-firmware describe --tags --always --abbrev=10) >> versions.csv

build-u_boot "${DEFCONFIG}" "${TUPLE}"

# Write Raspberry Pi boot config
cat << EOF > config.txt
kernel=u-boot.bin
boot_delay=0
boot_delay_ms=100
gpu_mem=16
enable_uart=1
EOF

if [ "${TUPLE}" = "aarch64-linux-gnu" ]
then
    echo "arm_64bit=1" >> config.txt
fi

if [ "${CHIP_ID}" = "bcm2711" ]; then
    # Copy Raspberry Pi 4 boot files
    cp -v rpi-firmware/boot/fixup4.dat \
          rpi-firmware/boot/fixup4x.dat \
          rpi-firmware/boot/fixup4cd.dat \
          rpi-firmware/boot/fixup4db.dat \
          rpi-firmware/boot/start4.elf \
          rpi-firmware/boot/start4x.elf \
          rpi-firmware/boot/start4cd.elf \
          rpi-firmware/boot/start4db.elf \
          rpi-firmware/boot/bootcode.bin \
          .
else
    # Copy Raspberry Pi boot files
    cp -v rpi-firmware/boot/fixup.dat \
          rpi-firmware/boot/fixup_x.dat \
          rpi-firmware/boot/fixup_cd.dat \
          rpi-firmware/boot/fixup_db.dat \
          rpi-firmware/boot/start.elf \
          rpi-firmware/boot/start_x.elf \
          rpi-firmware/boot/start_cd.elf \
          rpi-firmware/boot/start_db.elf \
          rpi-firmware/boot/bootcode.bin \
          .
fi

# Magic thing to get debug output
sed -i -e "s/BOOT_UART=0/BOOT_UART=1/" bootcode.bin

# Create empty FAT partition
rm -f vfat.img
fallocate -l 28MiB vfat.img
mkfs.vfat vfat.img

# Copy boot files to FAT partition
mcopy -v -i vfat.img u-boot/u-boot.bin config.txt fixup*.dat start*.elf bootcode.bin ::

# Copy FAT partition to image
dd if=vfat.img of=tmp.img bs=1K seek=4K conv=notrunc
